/**
 * 解析文件
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * 将文件解析成对应的有向图的邻接矩阵
 */

public class FileParsing {
    ArrayList<String> letters;

    public FileParsing() {
        this.letters = new ArrayList<>();
    }

    public AdjacencyMatrix parsingFile(String fileName) {
        String[] uniqueLetters = getFileUniqueLetter(fileName);

        AdjacencyMatrix adjacencyMatrix = new AdjacencyMatrix(uniqueLetters.length);
        adjacencyMatrix.setMatrixName(uniqueLetters);

        // 填充临界矩阵
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            int preLetterIndex = -1;
            int wordIndex = -1;
            while ((line = br.readLine()) != null) {
                // 按照空格拆分每行文本成单词数组
                String[] words = line.split("[^a-zA-Z]+");

                // 打印每个单词
                for (String word : words) {
                    if (preLetterIndex == -1) {
                        preLetterIndex = adjacencyMatrix.getIndexMatrix(word.toLowerCase());
                        continue;
                    }
                    wordIndex = adjacencyMatrix.getIndexMatrix(word.toLowerCase());
                    adjacencyMatrix.addEdge(preLetterIndex, wordIndex);
                    preLetterIndex = wordIndex;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return adjacencyMatrix;
    }

    private String[] getFileUniqueLetter(String fileName) {
        Set<String> uniqueWords = new HashSet<>();

        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按照非字母字符拆分每行文本成单词数组
                String[] words = line.split("[^a-zA-Z]+");

                // 将单词添加到集合中
                for (String word : words) {
                    if (!word.isEmpty()) {
                        uniqueWords.add(word.toLowerCase()); // 将单词转换为小写形式，以区分大小写
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回字符数组
        return uniqueWords.toArray(new String[0]);
    }
}
